// pages/cart/index.js
import { getSetting, chooseAddress, openSetting, showModal ,showToast} from "../../utils/asyncWx.js";
import regeneratorRuntime from '../../lib/runtime/runtime';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    address: {},
    cart: [],
    allChecked: false,
    totalPrice: 0,
    totalNum: 0

  },
  onShow(){
    const address = wx.getStorageSync('address');
    const cart = wx.getStorageSync('cart')|| [];
    this.setData({ address })
    this.setData({ cart })

  },
//收货地址
  async handleChooseAddress() {
    try {
      const res1 = await getSetting();
      const scopeAddress = res1.authSetting["scope.address"];
      if(scopeAddress === false){
        await openSetting()
      }
      let address = await chooseAddress();
      address.all = address.provinceName + address.cityName + address.countyName + address.detailInfo;

      wx.setStorageSync('address', address)

      
    } catch (error) {
      console.log(error)
      
    }

  },
//商品的选中
async handeItemChange(e){
  const goods_id =e.currentTarget.dataset.id;
  let {cart} = this.data;
  let index = cart.findIndex(v => v.goods_id === goods_id);
  cart[index].checked = !cart[index].checked;
  this.setCart(cart)
},

//商品结算
setCart(cart){
  let allChecked = true;
  // 1 总价格 总数量
  let totalPrice = 0;
  let totalNum = 0;
  cart.forEach(v => {
    if (v.checked) {
      totalPrice += v.num * v.goods_price;
      totalNum += v.num;
    } else {
      allChecked = false;
    }
  })
  // 判断数组是否为空
  allChecked = cart.length != 0 ? allChecked : false;
  this.setData({
    cart,
    totalPrice, totalNum, allChecked
  });
  wx.setStorageSync("cart", cart);

},

//商品全选状态
handleItemAllCheck(){
  let { cart,allChecked } = this.data;
  allChecked = !allChecked;
  cart.forEach(v=>v.checked = allChecked);
  this.setCart(cart)
},

 // 商品数量的编辑功能
 async handleItemNumEdit(e) {


  // 1 获取传递过来的参数 
  const { operation, id } = e.currentTarget.dataset;
  //console.log(e.currentTarget.dataset)
  // 2 获取购物车数组
  let { cart } = this.data;
  // 3 找到需要修改的商品的索引
  const index = cart.findIndex(v => v.goods_id === id);
  // 4 判断是否要执行删除
  if (cart[index].num === 1 && operation === -1) {
    // 4.1 弹窗提示
    const res = await showModal({ content: "您是否要删除？" });
    if (res.confirm) {
      cart.splice(index, 1);
      this.setCart(cart);
    }
  } else {
    // 4  进行修改数量
    cart[index].num += operation;
    // 5 设置回缓存和data中
    this.setCart(cart);
  }
},

//结算
async handlePay(){
   // 1 判断收货地址
   const {address,totalNum}=this.data;
   if(!address.userName){
     await showToast({title:"您还没有选择收货地址"});
     return;
   }
   // 2 判断用户有没有选购商品
   if(totalNum===0){
     await showToast({title:"您还没有选购商品"});
     return ;
   }
   // 3 跳转到 支付页面
   wx.navigateTo({
     url: '/pages/pay/index'
   });
     
}
})